﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Glorysoft.Auto.Xfw;
using Glorysoft.Auto.Xfw.Entities;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.EAPClient.Common;
using Glorysoft.EAP.EAPClient.Model;
using Newtonsoft.Json;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using static Glorysoft.EAP.EAPClient.Model.Body;
using static Glorysoft.EAP.EAPClient.ViewModel.SelectWaferViewModel;

namespace Glorysoft.EAP.EAPClient.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        public delegate void MessageNotifyHandler(MessageType type, string eqID, string message);//推送前端显示数据委托，推送的消息
        public delegate void EQPStatusHandler(EqpClientInfo eqp, EQPState state);//推送前端显示数据委托设备状态
        public event MessageNotifyHandler MessageEvent;
        public event EQPStatusHandler EQPStatusEvent;
        private readonly Logger ServiceLogger = XfwContext.EapLogger;
        public delegate void BackHandler();
        private DispatcherTimer timer;
        private DispatcherTimer timer2;
        private int currentRate = 0;
        private string startime;



        public void EQPStatusChangeEvent(EqpClientInfo eqp, EQPState state)
        {
            EQPStatusEvent(eqp, state);
        }

        private void EQPStatusChange(EqpClientInfo eqp, EQPState state)
        {
            try
            {
                if (eqp != null)
                {
                    bool isstate = state == EQPState.RUN;
                    eqp.EQPBGround = isstate ? "Red" : "Green";
                }
            }
            catch (Exception ex)
            {
                ShowMsg(MessageType.Error, ex.Message);
            }
        }
        public void MessageNotifyEvent(MessageType type, string eqID, string message)
        {
            MessageEvent(type, eqID, message);
        }
        private void MessageNotifyChange(MessageType type, string eqID, string message)
        {
            try
            {
                if (eqID != null)
                {
                    ShowMsg(MessageType.Error, "这个是一个测试", MessageOrigin.EAP);
                }
            }
            catch (Exception ex)
            {
                ShowMsg(MessageType.Error, ex.Message);
            }
        }
        public MainViewModel()
        {
            //这里执行多次，不建议将只运行一次的代码放入其中
            try
            {
                //Model.RunService.Current.MsgNotifier += ShowMsg;
                Model.RunService.Current.RGYHandl += ChangeRGY;
                startime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " , " + System.DateTime.Now.ToString("dddd");
                timer2 = new DispatcherTimer();
                timer2.Interval = new TimeSpan(0, 0, 0, 0, 1000);
                timer2.Tick += timer2_Tick;
                timer2.Start();
                //int seconds = Model.RunService.Current.EquipmentList.Count;
                //  IsProcessVisibity = Visibility.Visible;
                IslistVisibity = Visibility.Hidden;
                //timer = new DispatcherTimer();
                //timer.Interval = new TimeSpan(0, 0, 0, 0, 20);
                //timer.Tick += timer_Tick;
                //timer.Start();
                if (ClientInfo.EquipmentList != null && ClientInfo.EquipmentList.Count > 0)
                {
                    ClientInfo.EQPInfo = ClientInfo.EquipmentList[0];
                    EQPStatus.currenteqpid = ClientInfo.EquipmentList[0].EqpName;
                    ClientInfo.EquipmentList[0].MouseMargin = "10,0,0,0";
                    ClientInfo.EquipmentList[0].Vis = Visibility.Visible;
                    ClientInfo.EquipmentList[0].IsMouseOver = false;
                }

            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        #region 属性
        private static readonly Lazy<MainViewModel> Lazy = new Lazy<MainViewModel>(() => new MainViewModel());
        public static MainViewModel Current
        {
            get
            {
                return Lazy.Value;
            }
        }
        private string CopyMsg = "";
        private object lockobj = new object();
        private Thread thread;
        public Model.RunService ClientInfo
        {
            get
            {
                return Model.RunService.Current;
            }
        }

        ///// <summary>
        ///// 进度条
        ///// </summary>
        //private Visibility isProcessVisibity;
        //public Visibility IsProcessVisibity
        //{
        //    get { return isProcessVisibity; }
        //    set
        //    {
        //        isProcessVisibity = value;
        //        RaisePropertyChanged("IsProcessVisibity");
        //    }
        //}
        /// <summary>
        /// 数据展示，进度条加载完成后显示
        /// </summary>
        private Visibility islistVisibity;
        public Visibility IslistVisibity
        {
            get { return islistVisibity; }
            set
            {
                islistVisibity = value;
                RaisePropertyChanged("IslistVisibity");
            }
        }
        /// <summary>
        /// 启动时间
        /// </summary>
        private string currentDate;
        public string CurrentDate
        {
            get { return currentDate; }
            set
            {
                currentDate = value;
                RaisePropertyChanged("CurrentDate");
            }
        }
        /// <summary>
        /// 实时时间
        /// </summary>
        private string nowDate;
        public string NowDate
        {
            get { return nowDate; }
            set
            {
                nowDate = value;
                RaisePropertyChanged("NowDate");
            }
        }
        /// <summary>
        /// 版本号
        /// </summary>
        private string ver = "Ver " + Application.ResourceAssembly.GetName().Version.ToString();
        public string Ver
        {
            get { return ver; }
            set
            {
                ver = value;
                RaisePropertyChanged("Ver");
            }
        }
        /// <summary>
        /// 扫描历史选中位置
        /// </summary>
        private InstantMsg _MainItemSelected;
        public InstantMsg MainItemSelected
        {
            get { return _MainItemSelected; }
            set
            {
                _MainItemSelected = value;
                RaisePropertyChanged("MainItemSelected");
            }
        }

        private string _RGYColor = Consts.YELLOW;
        public string RGYColor
        {
            get
            {
                return _RGYColor;
            }
            set
            {
                _RGYColor = value;
                RaisePropertyChanged("RGYColor");
            }
        }
        private string lotid;
        public string Lotid
        {
            get
            {
                return lotid;
            }
            set
            {
                lotid = value;
                RaisePropertyChanged("LotId");
            }
        }
        private string probercardid;
        public string Probercardid
        {
            get
            {
                return probercardid;
            }
            set
            {
                probercardid = value;
                RaisePropertyChanged("ProberCardId");
            }
        }
        private Visibility btnok;
        public Visibility BtnOk
        {
            get { return btnok; }
            set
            {
                btnok = value;
                RaisePropertyChanged("BtnOk");
            }
        }
        private Visibility btnclean;
        public Visibility Btnclean
        {
            get { return btnclean; }
            set
            {
                btnclean = value;
                RaisePropertyChanged("Btnclean");
            }
        }
        private bool alignmentyes;
        public bool AlignmentYes
        {
            get { return alignmentyes; }
            set
            {
                alignmentyes = value;
                RaisePropertyChanged("Alignment");
            }
        }

        private bool alignmentno = true;
        public bool AlignmentNo
        {
            get { return alignmentno; }
            set
            {
                alignmentno = value;
                RaisePropertyChanged("Alignment");
            }
        }
        //对针字段
        private string alignment;
        public string Alignment
        {
            get { return alignment; }
            set
            {
                alignment = value;
                RaisePropertyChanged("Alignment");
            }
        }


        private bool autoSelectWaferTest = true;
        public bool AutoSelectWaferTest
        {
            get { return autoSelectWaferTest; }
            set
            {
                autoSelectWaferTest = value;
                RaisePropertyChanged("ChipSelect");
            }
        }

        private bool manualSelectWaferTest;
        public bool ManualSelectWaferTest
        {
            get { return manualSelectWaferTest; }
            set
            {
                manualSelectWaferTest = value;
                RaisePropertyChanged("ChipSelect");
            }
        }
        //选片字段
        private string chipSelect;
        public string ChipSelect
        {
            get { return chipSelect; }
            set
            {
                chipSelect = value;
                RaisePropertyChanged("ChipSelect");
            }
        }
        private bool aautoSelectWaferTest;
        public bool aAutoSelectWaferTest
        {
            get { return aautoSelectWaferTest; }
            set
            {
                aautoSelectWaferTest = value;
                RaisePropertyChanged("ChipSelect");
            }
        }

        private bool amanualSelectWaferTest = true;
        public bool aManualSelectWaferTest
        {
            get { return amanualSelectWaferTest; }
            set
            {
                amanualSelectWaferTest = value;
                RaisePropertyChanged("ChipSelect");
            }
        }
        //针痕检测字段
        private string needlemark;

        public string Needlemark
        {
            get { return needlemark; }
            set
            {
                needlemark = value;
                RaisePropertyChanged("Needlemark");
            }
        }

        private bool checkZHYes;
        public bool CheckZHYes
        {
            get { return checkZHYes; }
            set
            {
                checkZHYes = value;
                RaisePropertyChanged("Needlemark");
            }
        }

        private bool checkZHNo = true;
        public bool CheckZHNo
        {
            get { return checkZHNo; }
            set
            {
                checkZHNo = value;
                RaisePropertyChanged("Needlemark");
            }
        }
        private string testmode;
        public string TestMode
        {
            get { return testmode; }
            set
            {
                testmode = value;
                RaisePropertyChanged("TestMode");
            }
        }
        static string AccountArray = "Sequential-[全测];Sample-[抽测];Assign-[指定位置测试]";
        public List<string> testmodelist = new List<string>(AccountArray.Split(';'));//字符串转List

        public List<string> TestModeList
        {
            get { return testmodelist; }
            set
            {
                testmodelist = value;
                RaisePropertyChanged("TestModeList");
            }
        }
        #endregion
        #region 方法
        public void ShowMsg(MessageType type, string detail, MessageOrigin origin = MessageOrigin.EAP)
        {
            try
            {
                if (ClientInfo.EQPInfo.LotList[0].MSG.Count >= 500)
                {
                    ClientInfo.EQPInfo.LotList[0].MSG.RemoveAt(500);
                }
                ClientInfo.EQPInfo.LotList[0].MSG.Insert(0, new InstantMsg()
                {
                    CurTime = DateTime.Now,
                    FrontColor = Consts.MsgColorMap[type],
                    Title = origin,
                    Detail = detail
                });
                MainItemSelected = ClientInfo.EQPInfo.LotList[0].MSG[ClientInfo.EQPInfo.LotList[0].MSG.Count - 1];
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        public void InitData()
        {
            try
            {

                //string HostName = Dns.GetHostName(); //得到主机名
                //IPHostEntry IpEntry = Dns.GetHostEntry(HostName); //得到主机IP
                //foreach (var item in IpEntry.AddressList)
                //{
                //    if (item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                //    {
                //        Ipadr = item.ToString();
                //    }
                //}

                Scheduler.Initialize();
                // ShowMsg(MessageType.Error, "这个是一个测试", MessageOrigin.EAP);
                Scheduler.Add("InitConnect", 5, ScheduleOptions.Loop, new Action<object>(obj => InitConnect()), null);

            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        #region Properties
        private int successRate = 100;
        public int SuccessRate
        {
            get
            {
                return successRate;
            }
            set
            {
                if (value != successRate)
                {
                    successRate = value;
                    RaisePropertyChanged("SuccessRate");
                }
            }
        }
        #endregion
        /// <summary>
        /// 加载进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                currentRate++;
                SuccessRate = currentRate * 100 / 100;
                if (SuccessRate == 110)
                {
                    ClientInfo.EQPInfo.IsProcessVisibity = Visibility.Visible;
                    IslistVisibity = Visibility.Visible;
                    timer.Stop();

                    Thread t = new Thread(new ThreadStart(Refresh2));
                    t.Start();

                }
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        /// <summary>
        /// 实时时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                CurrentDate = Consts.GetTranslation("Msg_StartTime") + "：" + startime;
                //  NowDate = Consts.GetTranslation("Msg_CurTme") + "：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " , " + DateTime.Now.ToString("dddd");
                NowDate = Consts.GetTranslation("Msg_CurTme") + "：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        /// <summary>
        /// 通知EAPServer,开启连接
        /// </summary>
        private void InitConnect()
        {
            try
            {
                EAPClient client = new EAPClient();
                var eqpId = ClientInfo.EQPInfo.TesterName;
                var _return = client.SendHeartBeat(eqpId);
                var conn = ClientInfo.EQPInfo.ConnStatus ? "conn" : "disconn"; //Client显示EAPServer的状态
                var eapconnStatus = Dict.Current.EAPConnStatus; //Server-Client断开发送消息标识

                if (_return != null && _return.ReturnCode == "OK")
                {
                    var list = JsonConvert.DeserializeObject<Response<Object>>(_return.ReturnMessage);
                    if (list == null || list.Body == null)
                    {
                        return;
                    }
                    var ocrstatus = list.Body.OCRConnStatus; //Server发送的ProberOCR状态
                    var connStatus = ClientInfo.EQPInfo.ProberStatus ? "1" : "-1"; //Client显示ProberOCR的状态

                    var returnMessage = list.Return.ReturnMessage; //Server发送的EAPServer状态

                    var ocrTesterStatus = list.Body.OCRTesterConnStatus;//Server发送的Tester OCR状态
                    var testerConnStatus = ClientInfo.EQPInfo.TesterStatus ? "1" : "-1"; ;//Client显示Tester OCR的状态
                    if (conn != returnMessage)
                    {
                        ClientInfo.EQPInfo.ConnStatus = true;
                        var messages = TranslateMsg.GetTranslation("Conn", "EAPServer");
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Conn, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                            ClientInfo.EQPInfo.Loginin = Visibility.Visible;
                        }
                        ClientInfo.EQPInfo.AuotoProcess = true;
                    }
                    if (ocrstatus != connStatus)
                    {
                        if (ocrstatus == "1")
                        {
                            ClientInfo.EQPInfo.ProberStatus = true;
                            var messages = TranslateMsg.GetTranslation("Conn", "OCR");
                            if (!(messages == null || messages.Count == 0))
                            {
                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Conn, messages[RunService.Current.ClientLanguage]);
                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                            }
                        }
                        else
                        {
                            ClientInfo.EQPInfo.ProberStatus = false;
                            var messages = TranslateMsg.GetTranslation("DisConn", "OCR");
                            if (!(messages == null || messages.Count == 0))
                            {
                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Error, messages[RunService.Current.ClientLanguage]);
                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                            }
                        }
                    }
                    if (ocrTesterStatus != testerConnStatus && Dict.Current.EAPName != "EAPServer" && Dict.Current.EAPName != "EAPTelAmida")  //使用daemon操作的type  EAPTelAmida
                    {
                        if (ocrTesterStatus == "1")
                        {
                            ClientInfo.EQPInfo.TesterStatus = true;
                            var messages = TranslateMsg.GetTranslation("Conn", "OCR-Tester");
                            if (!(messages == null || messages.Count == 0))
                            {
                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Conn, messages[RunService.Current.ClientLanguage]);
                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                            }
                        }
                        else
                        {
                            ClientInfo.EQPInfo.TesterStatus = false;
                            var messages = TranslateMsg.GetTranslation("DisConn", "OCR-Tester");
                            if (!(messages == null || messages.Count == 0))
                            {
                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Error, messages[RunService.Current.ClientLanguage]);
                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                            }
                        }
                    }
                    Dict.Current.EAPConnStatus = "0";
                }
                else
                {
                    if (eapconnStatus == "0")
                    {
                        Dict.Current.EAPConnStatus = "1";
                        ClientInfo.EQPInfo.ConnStatus = false;
                        var messages = TranslateMsg.GetTranslation("DisConn", "EAPServer");
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Error, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                        }
                        ClientInfo.EQPInfo.AuotoProcess = false;
                        ClientInfo.EQPInfo.ProberStatus = false;
                        ClientInfo.EQPInfo.BGround = "Red";
                        messages = TranslateMsg.GetTranslation("DisConn", "OCR");
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Error, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                        }
                        ClientInfo.EQPInfo.TesterStatus = false;
                        if (Dict.Current.EAPName == "EAPServer" || Dict.Current.EAPName == "EAPTelAmida") //FP3000 与amida MQ配置
                        {
                            messages = TranslateMsg.GetTranslation("DisConn", "Daemon");
                        }
                        else
                        {
                            messages = TranslateMsg.GetTranslation("DisConn", "OCR-Tester");
                        }
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Error, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        /// <summary>
        /// 关闭客户端
        /// </summary>
        private RelayCommand closeCmd;
        public RelayCommand CloseCmd
        {
            get
            {
                return closeCmd ?? (closeCmd = new RelayCommand(Close));
            }
        }


        /// <summary>
        /// <summary>
        private void Close()
        {
            try
            {
                if (CMessageBox.Show(Consts.GetTranslation("Msg_Exit"), Consts.GetTranslation("Msg_ConfirmInfo"), CMessageBoxButton.OKCancel) == CMessageBoxResult.OK)
                {
                    // DisConnectKVM();//关闭KVM
                    Hook k_hook = new Hook();
                    // k_hook.KeyHookStop();
                    k_hook.KeyHookStop();
                    k_hook = null;
                    System.Environment.Exit(0);
                    XfwContext.TerminateXfw();

                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
                ShowMsg(MessageType.Error, "异常" + ex.ToString(), MessageOrigin.EAP);
                System.Environment.Exit(0);
            }
        }
        private RelayCommand languageCmd;
        public RelayCommand LanguageCmd
        {
            get
            {
                return languageCmd ?? (languageCmd = new RelayCommand(LanguageChange));
            }
        }
        /// <summary>
        /// <summary>
        private void LanguageChange()
        {
            try
            {
                if (ClientInfo.LanguageBtnTxt == "中文")
                {
                    ClientInfo.LanguageBtnTxt = "En";
                    ClientInfo.ClientLanguage = "EN";
                }
                else if (ClientInfo.LanguageBtnTxt == "En")
                {
                    ClientInfo.LanguageBtnTxt = "中文";
                    ClientInfo.ClientLanguage = "CN";
                }
                if (ClientInfo.ClientLanguage == "CN")
                {
                    ClientInfo.LisenBtnContext = "登录";

                    if (ClientInfo.Lbl_CarrierID == "载具" || ClientInfo.Lbl_CarrierID == "Carrier")
                        ClientInfo.Lbl_CarrierID = "载具";
                    if (ClientInfo.Lbl_CarrierID == "批次" || ClientInfo.Lbl_CarrierID == "LotID")
                        ClientInfo.Lbl_CarrierID = "批次";

                    if (ClientInfo.TrackOutBtn == "LotEnd" || ClientInfo.TrackOutBtn == "批次结束")
                        ClientInfo.TrackOutBtn = "批次结束";
                    if (ClientInfo.TrackOutBtn == "TrackOut" || ClientInfo.TrackOutBtn == "出站")
                        ClientInfo.TrackOutBtn = "出站";
                }
                else
                {
                    ClientInfo.LisenBtnContext = "Login";

                    if (ClientInfo.Lbl_CarrierID == "载具" || ClientInfo.Lbl_CarrierID == "Carrier")
                        ClientInfo.Lbl_CarrierID = "Carrier";
                    if (ClientInfo.Lbl_CarrierID == "批次" || ClientInfo.Lbl_CarrierID == "LotID")
                        ClientInfo.Lbl_CarrierID = "LotID";

                    if (ClientInfo.TrackOutBtn == "LotEnd" || ClientInfo.TrackOutBtn == "批次结束")
                        ClientInfo.TrackOutBtn = "LotEnd";
                    if (ClientInfo.TrackOutBtn == "TrackOut" || ClientInfo.TrackOutBtn == "出站")
                        ClientInfo.TrackOutBtn = "TrackOut";

                }
                if (ClientInfo.EQPInfo.LotList[0].ListHearMsg == "实时信息" || ClientInfo.EQPInfo.LotList[0].ListHearMsg.Contains("Real-time"))
                {
                    ClientInfo.EQPInfo.LotList[0].ListHearMsg = Consts.GetTranslation("Msg_RealtimeInfo");
                    ClientInfo.EQPInfo.LotList[0].BoxHearMsg = Consts.GetTranslation("Msg_WaferInfo");
                }
            }
            catch (Exception ex)
            {
            }
        }
        private RelayCommand _RefreshCmd;
        public RelayCommand RefreshCmd
        {
            get
            {
                return _RefreshCmd ?? (_RefreshCmd = new RelayCommand(Refresh));
            }
        }
        /// <summary>
        /// <summary>
        private void Refresh()
        {
            try
            {
                Thread t = new Thread(new ThreadStart(Refresh2));
                t.Start();
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        List<string> Search()
        {
            try
            {
                List<string> list = new List<string>();

                for (int i = 0; i < 10; i++)
                {
                    list.Add("我是第" + i.ToString() + "个");
                    Thread.Sleep(1000);
                }
                return list;
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常" + ex.Message);
                return null;
            }
        }

        private void Refresh2()
        {

            try
            {
                //SubBaseForm sb = new SubBaseForm("正在加载数据,请稍候...");
                //SubBaseForm.DelegateNonParmAndHasReturn my = new SubBaseForm.DelegateNonParmAndHasReturn(Search);
                //object obj = sb.NonParmAndHasReturnMethod(my);
                //if (obj != null)
                //{
                //    List<string> list = obj as List<string>;
                //    string tempStr = string.Empty;
                //    foreach (string str in list)
                //    {
                //        tempStr += str;
                //    }
                //    MessageBox.Show(tempStr);
                //}
                ClientInfo.RefreshName = "&#xf146;  刷新中...";
                ClientInfo.RefreshStatus = false;
                System.Threading.Thread.Sleep(1000);
                if (ClientInfo.EquipmentList != null && ClientInfo.EquipmentList.Count > 0)
                {
                    foreach (EqpClientInfo entity in ClientInfo.EquipmentList)
                    {
                        ClientInfo.RefreshName = entity.EqpName + "...";
                        entity.ConnStatus = false;
                        entity.EQPConnStatus = false;
                        //System.Threading.Thread.Sleep(100);
                        var _client = new EAPClient();
                        // _client.SendConnect(new ConnectModel() { EQPID = entity.EqpName });
                        var _return = _client.SendConnect(new ConnectModel() { EQPID = entity.EqpName });
                        if (_return != null && _return.ReturnCode == "OK")
                            entity.ConnStatus = true;
                        System.Threading.Thread.Sleep(100);
                    }
                    System.Threading.Thread.Sleep(1000);
                    ClientInfo.RefreshName = "&#xf146;  刷新成功";
                    System.Threading.Thread.Sleep(2000);
                    ClientInfo.RefreshName = "&#xf146;  刷新";
                    ClientInfo.RefreshStatus = true;
                }
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
                ClientInfo.RefreshName = "&#xf146;  刷新";
                ClientInfo.RefreshStatus = true;
            }


        }
        /// <summary>
        /// 打开选片页面
        /// </summary>
        private RelayCommand<string> selectCmd;
        public RelayCommand<string> SelectCmd
        {
            get
            {
                return selectCmd ?? (selectCmd = new RelayCommand<string>(SelectWafer));
            }
        }


        public void SelectWafer(string obj)
        {
            try
            {
                Controller.ShowWindow(new SelectWaferViewModel());
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }
        }
        private RelayCommand getlotinfoCmd;
        public RelayCommand GetlotinfoCmd
        {
            get
            {
                return getlotinfoCmd ?? (getlotinfoCmd = new RelayCommand(Getlotinfo));
            }
        }
        /// <summary>
        /// 获取批次信息事件
        /// </summary>
        private void Getlotinfo()
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                try
                {
                    if (string.IsNullOrEmpty(Current.Lotid))
                    {
                        MessageBox.Show(Consts.GetTranslation("Msg_LotidInputInfo"), Consts.GetTranslation("Msg_ConfirmInfo"), MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    C_LotInfo lot = new C_LotInfo();
                    // type1  EAPServer &   EAPServer_OCR
                    if (Dict.Current.EAPName == "EAPServer" || Dict.Current.EAPName == "EAPServer_OCR" || Dict.Current.EAPName == "EAPServer_ETS88")
                    {
                        //Type1, LOT信息获取
                        if (string.IsNullOrEmpty(Current.Probercardid))
                        {
                            MessageBox.Show(Consts.GetTranslation("Msg_ProbercarIdInputInfo"), Consts.GetTranslation("Msg_ConfirmInfo"), MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        if (AlignmentYes == true)
                        {
                            Alignment = "Y";
                        }
                        else
                        {
                            Alignment = "N";
                        }
                        if (AutoSelectWaferTest == true)
                        {
                            ChipSelect = "Y";
                        }
                        else
                        {
                            ChipSelect = "N";
                        }
                        if (checkZHYes == true)
                        {
                            Needlemark = "Y";
                        }
                        else
                        {
                            Needlemark = "N";
                        }
                        if (CMessageBox.Show(Consts.GetTranslation("Msg_Confirm") + "\r\n" + "Lot Id：" + Current.Lotid + "\r\n" + "ProberCardId：" + Current.Probercardid + "\r\n" + "针卡校准提醒：" + "此针卡是否已通知工程师进行校准？", Consts.GetTranslation("Msg_ConfirmInfo"), CMessageBoxButton.OKCancel) == CMessageBoxResult.OK)
                        {
                           
                 
                            var facilityId = ClientInfo.EQPInfo.FacilityId;
                            var eqpname = ClientInfo.EQPInfo.TesterName;
                            var testmode = TestMode;
                            EAPClient eapclient = new EAPClient();
                            //调用server getlotinfo
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            Dictionary<string, string> paramss = new Dictionary<string, string>();
                            paramss.Add("Lotid", Current.Lotid.ToUpper());
                            paramss.Add("eqpname", eqpname);
                            paramss.Add("UserId", ClientInfo.EQPInfo.LotList[0].UserId);
                            paramss.Add("facilityId", facilityId);
                            paramss.Add("proberCardId", Current.Probercardid.ToUpper());
                            paramss.Add("alignment", Alignment);
                            paramss.Add("testmode", testmode);
                            SubBaseForm sb = new SubBaseForm("正在加载数据,请稍候...");
                            SubBaseForm.DelegateHasParmAndHasReturn my = new SubBaseForm.DelegateHasParmAndHasReturn(eapclient.GetCarrierLotInfo);
                            var obj = sb.HasParmAndHasReturnMethod(my, paramss);
                            // var _return = eapclient.GetCarrierLotInfo(Current.Lotid.ToUpper(), eqpname, ClientInfo.EQPInfo.LotList[0].UserId, facilityId, Current.Probercardid.ToUpper(), Alignment);
                            sw.Stop();

                            ServiceLogger.Debug($"调用GetCarrierLotInfo获取lot信息，耗时为:{sw.ElapsedMilliseconds}");
                            if (obj != null)
                            {
                                var list = JsonConvert.DeserializeObject<Response<Object>>(obj.ReturnMessage);
                                if (list == null)
                                {
                                    MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfo"), MessageOrigin.EAP);
                                    return;
                                }
                                if (list.Return.ReturnCode == "OK")
                                {
                                    sw.Start();
                                    var msgbody = list.Body;


                                    if (!string.IsNullOrEmpty(msgbody.SamplePrompts))
                                    {
                                        msgbody.samplePrompts = JsonConvert.DeserializeObject<List<samplePrompts>>(msgbody.SamplePrompts);
                                    }

                                    msgbody.Units = JsonConvert.DeserializeObject<List<unitsInfo>>(msgbody.UnitList);
                                    ClientInfo.EQPInfo.LotList[0].LotId = msgbody.LotId;
                                    ClientInfo.EQPInfo.LotList[0].LotsStatus = msgbody.LotStatus;
                                    ClientInfo.EQPInfo.LotList[0].Qty = msgbody.WaferCount;
                                    ClientInfo.EQPInfo.LotList[0].Priority = msgbody.Priority;
                                    ClientInfo.EQPInfo.LotList[0].ProductId = msgbody.ProductId;
                                    ClientInfo.EQPInfo.LotList[0].StageId = msgbody.StageId;
                                    ClientInfo.EQPInfo.LotList[0].ProberRecipe = msgbody.ProberRecipe;
                                    ClientInfo.EQPInfo.LotList[0].TesterProgram = msgbody.TesterProgram;
                                    ClientInfo.EQPInfo.LotList[0].Probercard = Current.Probercardid;
                                    ClientInfo.EQPInfo.LotList[0].rcflag = msgbody.rcflag;
                                    ClientInfo.EQPInfo.LotList[0].SlotMaps = new ObservableCollection<SLotMap>();
                                    var boolRuncard = ClientInfo.EQPInfo.LotList[0].rcflag;
                                    for (int i = 1; i <= 25; i++)
                                    {
                                        ClientInfo.EQPInfo.LotList[0].SlotMaps.Add(new SLotMap() { SlotId = $"{i}", waferState = WaferState.WaferNothing.ToString() });//eaf5fd
                                    }
                                    var testid = "";
                                    var mesTestid = "";
                                    // 定义测试的id属性
                                                    //if (boolRuncard== "Y")
                                                    //{
                                                    //    foreach (var item in msgbody.samplePrompts)
                                                    //    {
                                                    //        testid += item.position + ";";
                                                    //    }
                                                    //}
                                                    //else
                                                    //{
                                                    //    foreach (var item in msgbody.Units)
                                                    //    {
                                                    //        var waferinfo = ClientInfo.EQPInfo.LotList[0].SlotMaps.First(o => o.SlotId == item.position);
                                                    //        waferinfo.SlotId = item.position;
                                                    //        waferinfo.waferId = item.unitId;
                                                    //        waferinfo.waferState = WaferState.WaferIn.ToString();
                                                    //        waferinfo.runState = WaferState.Waiting.ToString();
                                                    //        testid += waferinfo.SlotId + ";";
                                                    //    }
                                                    //}
                                    var unitidlist = "";// 定义测试MES的unitid属性  
                                    foreach (var item in msgbody.Units)
                                    {
                                        var waferinfo = ClientInfo.EQPInfo.LotList[0].SlotMaps.First(o => o.SlotId == item.position);
                                        waferinfo.SlotId = item.position;
                                        waferinfo.waferId = item.unitId;
                                        waferinfo.waferState = WaferState.WaferIn.ToString();
                                        waferinfo.runState = WaferState.Waiting.ToString();
                                        testid += waferinfo.SlotId + ";";
                                        unitidlist += waferinfo.waferId + ";";
                                    }

                                    //testid = "1;2;3;4;5;6";
                                    //  ClientInfo.EQPInfo.LotList[0].SlotMaps = ClientInfo.EQPInfo.LotList[0].SlotMaps;                                          
                                    //获取批次成功后，清除Probercardid、Lotid
                                    ClientInfo.EQPInfo.IsProcessVisibity = Visibility.Collapsed;
                                    MainViewModel.Current.Probercardid = "";
                                    MainViewModel.Current.Lotid = "";
                                    ClientInfo.EQPInfo.BtnOk = Visibility.Collapsed;
                                    MainViewModel.Current.ShowMsg(MessageType.Normal, ClientInfo.EQPInfo.LotList[0].LotId + "：" + Consts.GetTranslation("Msg_GetLotinfoOK"), MessageOrigin.EAP);
                                    var TestModevalue = TestMode.Split("-")[0];
                                    Dict.Current.TestModevalue = TestModevalue;
                                    Dict.Current.SelectWaferIdList = "";
                                    Dict.Current.CheckZHMode = Needlemark;
                                    Dict.Current.unitIdList = unitidlist;
                                    string samplePromptsid = "";
                                    var selectid = "";
                                    if (TestModevalue == "Sequential")//按MES值，全测
                                    {
                                        if (true)
                                        //if (rcflag == "Y")
                                        {
                                            if (!(msgbody.samplePrompts == null) && msgbody.samplePrompts.Count > 0)
                                            {
                                                if (msgbody.samplePrompts.Count() != msgbody.Units.Count())
                                                {
                                                    foreach (var item in msgbody.samplePrompts)
                                                    {
                                                        samplePromptsid += item.position + ";";
                                                    }
                                                    Dict.Current.TestModevalue = "Sample";
                                                }
                                                else
                                                {

                                                    Dict.Current.TestModevalue = "Sequential";
                                                    foreach (var item in msgbody.Units)
                                                    {
                                                        samplePromptsid += item.position + ";";
                                                    }
                                                }
                                                selectid = samplePromptsid.TrimEnd(';');
                                            }
                                        }
                                        ClientInfo.EQPInfo.LotList[0].TestID = testid.Replace(";", " ");  //前台显示测试的id ,id 之间用空格处理了                                                                   
                                  
                                        if (Needlemark == "Y")
                                        {
                                            var markvalue = testid.TrimEnd(';').Split(";");
                                            if (markvalue.Count() > 3)
                                            {
                                                //取值首、中、尾 三片
                                                var First = markvalue[0];
                                                var Medium = markvalue[markvalue.Length / 2];
                                                var Last = markvalue[markvalue.Length - 1];
                                                Dict.Current.SelectWaferIdList = First + ";" + Medium + ";" + Last;
                                            }
                                            else
                                            {
                                                Dict.Current.SelectWaferIdList = testid.TrimEnd(';');
                                            }
                                        }
                                        else
                                        {
                                            Dict.Current.SelectWaferIdList = "";
                                        }
                                        Dictionary<string, string> messages = null;
                                        var cassetteSlotId = "";
                                        Return result = null;
                                        if (Dict.Current.EAPName == "EAPServer_OCR")
                                        {
                                            result = eapclient.SelectWaferIDFP3000(ClientInfo.EQPInfo.ProberName, selectid, Dict.Current.TestModevalue, "true", Dict.Current.SelectWaferIdList, unitidlist);
                                        }
                                        else {
                                            result = eapclient.SelectWaferID(ClientInfo.EQPInfo.ProberName, selectid, selectid, "true", Dict.Current.SelectWaferIdList, unitidlist);
                                        }
                                      
                                        if (result.ReturnCode == "0")
                                        {
                                            ClientInfo.EQPInfo.LotList[0].TestID = selectid;
                                            messages = TranslateMsg.GetTranslation("SelectWaferIDOK", selectid);
                                            if (!(messages == null || messages.Count == 0))
                                            {
                                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                            }
                                            if (string.IsNullOrEmpty(Dict.Current.SelectWaferIdList))
                                            {
                                                Dict.Current.SelectWaferIdList = "0";//不选片，打印成0
                                            }
                                            messages = TranslateMsg.GetTranslation("SelectNeedleMarkDetectionWaferIdOK", Dict.Current.SelectWaferIdList);
                                            if (!(messages == null || messages.Count == 0))
                                            {
                                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                            }
                                            ServiceLogger.Debug($"选择针痕检测WaferId为:{Dict.Current.SelectWaferIdList.TrimEnd(';')}");
                                            //  MainViewModel.Current.ShowMsg(MessageType.Info, ClientInfo.EQPInfo.LotList[0].LotId + "：" + "Select No" + tempID.TrimEnd(';'), MessageOrigin.EAP);
                                            //  Dict.Current.SelectWaferIdList = selectid;

                                            // 进行筛选针痕检测的片 
                                            //  lot.NeedleMarkDetectionSelectWaferBox();
                                        }
                                        else
                                        {
                                            messages = TranslateMsg.GetTranslation("SelectWaferIDNG");
                                            if (!(messages == null || messages.Count == 0))
                                            {
                                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                            }
                                        }

                                    }
                                    //页面选择Y,MA选片  
                                    else
                                    {
                                        //进行筛片                                                                     
                                        lot.SelectWaferBox();
                                    }
                                    sw.Stop();
                                    ServiceLogger.Debug($"调用GetCarrierLotInfo 结果不为空处理逻辑，耗时为:{sw.ElapsedMilliseconds}");
                                }
                                else
                                    MainViewModel.Current.ShowMsg(MessageType.Error, "MES>" + list.Return.ReturnMessage, MessageOrigin.EAP);
                            }
                            else
                            {
                                MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfo"), MessageOrigin.EAP);
                            }
                        }
                    }
                    //Type2 EAPTelKeysight  EAPTelKeysight2 LOT信息获取
                    else if (Dict.Current.EAPName == "EAPTelKeysight" || Dict.Current.EAPName == "EAPTelKeysight2")
                    {
                        if (CMessageBox.Show(Consts.GetTranslation("Msg_Confirm") + "Lot Id：" + Current.Lotid, Consts.GetTranslation("Msg_ConfirmInfo"), CMessageBoxButton.OKCancel) == CMessageBoxResult.OK)
                        {
                            var facilityId = ClientInfo.EQPInfo.FacilityId;
                            var eqpname = ClientInfo.EQPInfo.TesterName;
                            EAPClient eapclient = new EAPClient();
                            //调用server getlotinfo
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            Dictionary<string, string> paramss = new Dictionary<string, string>();
                            paramss.Add("Lotid", Current.Lotid.ToUpper());
                            // paramss.Add("proberCardId", Current.Probercardid.ToUpper());
                            paramss.Add("eqpname", eqpname);
                            paramss.Add("UserId", ClientInfo.EQPInfo.LotList[0].UserId);
                            paramss.Add("facilityId", facilityId);
                            paramss.Add("proberCardId", "None");
                            paramss.Add("alignment", "None");
                            paramss.Add("testmode", "None");
                            SubBaseForm sb = new SubBaseForm("正在加载数据,请稍候...");
                            SubBaseForm.DelegateHasParmAndHasReturn my = new SubBaseForm.DelegateHasParmAndHasReturn(eapclient.GetCarrierLotInfo);
                            var obj = sb.HasParmAndHasReturnMethod(my, paramss);
                            //var _return = eapclient.GetCarrierLotInfo(Current.Lotid.ToUpper(), eqpname, ClientInfo.EQPInfo.LotList[0].UserId, facilityId, "None", "None");                                            
                            sw.Stop();
                            ServiceLogger.Debug($"Type2 调用GetCarrierLotInfo获取lot信息，耗时为:{sw.ElapsedMilliseconds}");
                            if (obj == null)
                            {
                                MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfoByType2"), MessageOrigin.EAP);
                                return;
                            }
                            var list = JsonConvert.DeserializeObject<Response<Object>>(obj.ReturnMessage);
                            if (list == null)
                            {
                                ServiceLogger.Debug($"_return: is null,{Dict.Current.EAPName}");
                                MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfoByType2"), MessageOrigin.EAP);
                                return;
                            }
                            if (list.Return.ReturnCode == "OK")
                            {
                                sw.Start();
                                var msgbody = list.Body;
                                msgbody.Units = JsonConvert.DeserializeObject<List<unitsInfo>>(msgbody.UnitList);
                                if (!string.IsNullOrEmpty(msgbody.SamplePrompts))
                                {
                                    msgbody.samplePrompts = JsonConvert.DeserializeObject<List<samplePrompts>>(msgbody.SamplePrompts);
                                }
                                ClientInfo.EQPInfo.LotList[0].LotId = msgbody.LotId;
                                ClientInfo.EQPInfo.LotList[0].LotsStatus = msgbody.LotStatus;
                                ClientInfo.EQPInfo.LotList[0].Qty = msgbody.WaferCount;
                                ClientInfo.EQPInfo.LotList[0].Priority = msgbody.Priority;
                                ClientInfo.EQPInfo.LotList[0].ProductId = msgbody.ProductId;
                                ClientInfo.EQPInfo.LotList[0].StageId = msgbody.StageId;
                                ClientInfo.EQPInfo.LotList[0].ProberRecipe = msgbody.ProberRecipe;
                                ClientInfo.EQPInfo.LotList[0].TesterProgram = msgbody.TesterProgram;
                                // ClientInfo.EQPInfo.LotList[0].Probercard = Current.Probercardid;//TYPE 2 无Probercard

                                ClientInfo.EQPInfo.LotList[0].SlotMaps = new ObservableCollection<SLotMap>();

                                for (int i = 1; i <= 25; i++)
                                {
                                    ClientInfo.EQPInfo.LotList[0].SlotMaps.Add(new SLotMap() { SlotId = $"{i}", waferState = WaferState.WaferNothing.ToString() });//eaf5fd
                                }
                                foreach (var item in msgbody.Units)
                                {
                                    var waferinfo = ClientInfo.EQPInfo.LotList[0].SlotMaps.First(o => o.SlotId == item.position);
                                    waferinfo.waferId = item.unitId;
                                    waferinfo.waferState = WaferState.WaferIn.ToString();
                                    waferinfo.runState = WaferState.Waiting.ToString();

                                }

                                //获取批次成功后，清除Lotid   
                                MainViewModel.Current.Lotid = "";
                                MainViewModel.Current.Probercardid = "";
                                ClientInfo.EQPInfo.BtnOk = Visibility.Collapsed;
                                MainViewModel.Current.ShowMsg(MessageType.Normal, ClientInfo.EQPInfo.LotList[0].LotId + "：" + Consts.GetTranslation("Msg_GetLotinfoOK"), MessageOrigin.EAP);
                                // true：EAP由mes信息自动传值，false:打开新的窗体，OP手动选片。  ps:选片的值需要client ->server-> OCR,。
                                string IsAll = "N";
                                if (AutoSelectWaferTest == true)
                                {
                                    var testid = "";// 定义测试的id属性
                                    var testid_special = "";// 定义al区特殊产品选片测试的id属性
                                    if (string.IsNullOrEmpty(msgbody.SamplePrompts))
                                    {
                                        foreach (var item in msgbody.Units)
                                        {
                                            testid += item.position + ";";
                                        }
                                        IsAll = "Y";
                                    }
                                    else
                                    {

                                        //20221008 wat设备F1&F2区域同步的eap自动选片
                                        //if (facilityId == "F2")
                                        //{
                                        //    foreach (var item in msgbody.Units)
                                        //    {
                                        //        testid += item.position + ";";
                                        //    }
                                        //}
                                        //else
                                        //{
                                        foreach (var item in msgbody.samplePrompts)
                                        {
                                            testid += item.position + ";";
                                        }
                                    }
                                    //}
                                    //20220311取消wat特殊选片要求
                                    //string[] namelist = Dict.Current.SpecialRecipeName.Split(';');
                                    //foreach (var itemname in namelist)
                                    //{
                                    //    if (ClientInfo.EQPInfo.LotList[0].TesterProgram == itemname)
                                    //    {
                                    //        var qty = ClientInfo.EQPInfo.LotList[0].Qty;
                                    //        foreach (var item in msgbody.Units)
                                    //        {
                                    //            testid_special += item.position + ";";
                                    //        }
                                    //        if (Convert.ToInt32(qty) > 6)
                                    //        {
                                    //            //调用特殊的选片规则方法
                                    //            testid = SelectWaferIdByWAT(qty, testid_special);
                                    //        }
                                    //        else
                                    //        {
                                    //            testid = testid_special;
                                    //        }
                                    //    }
                                    //}
                                    ClientInfo.EQPInfo.LotList[0].TestID = testid.Replace(";", " ");  //前台显示测试的id ,id 之间用空格处理了
                                    //EAP获取片号进行传值
                                    var selectid = testid.TrimEnd(';');
                                    Dictionary<string, string> messages = null;
                                    var result = eapclient.SelectWaferID(ClientInfo.EQPInfo.ProberName, selectid, selectid, "true", "",null, IsAll);
                                    if (result.ReturnCode == "0")
                                    {
                                        messages = TranslateMsg.GetTranslation("SelectWaferIDOK", selectid);
                                        if (!(messages == null || messages.Count == 0))
                                        {
                                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                        }
                                        //  MainViewModel.Current.ShowMsg(MessageType.Info, ClientInfo.EQPInfo.LotList[0].LotId + "：" + "Select No" + tempID.TrimEnd(';'), MessageOrigin.EAP);

                                    }
                                    else
                                    {
                                        messages = TranslateMsg.GetTranslation("SelectWaferIDNG");
                                        if (!(messages == null || messages.Count == 0))
                                        {
                                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                        }
                                    }
                                }
                                else
                                {
                                    //进行筛片                                                            
                                    lot.SelectWaferBox();
                                }

                                // lot.NeedleMarkDetectionSelectWaferBox();//进行针痕检测选片
                                sw.Stop();
                                ServiceLogger.Debug($"Type2 调用GetCarrierLotInfo 结果不为空处理逻辑，耗时为:{sw.ElapsedMilliseconds}");
                            }

                            else
                                MainViewModel.Current.ShowMsg(MessageType.Error, "MES>" + list.Return.ReturnMessage, MessageOrigin.EAP);
                        }
                        else
                        {
                            ServiceLogger.Debug($"_return: is null,{Dict.Current.EAPName}");
                            MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfoByType2"), MessageOrigin.EAP);

                        }
                    }
                    else
                    {
                        //type3 bitcoin
                        if (string.IsNullOrEmpty(Current.Probercardid))
                        {
                            MessageBox.Show(Consts.GetTranslation("Msg_ProbercarIdInputInfo"), Consts.GetTranslation("Msg_ConfirmInfo"), MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        if (CMessageBox.Show(Consts.GetTranslation("Msg_Confirm") + "\r\n" + "Lot Id：" + Current.Lotid + "\r\n" + "ProberCardId：" + Current.Probercardid, Consts.GetTranslation("Msg_ConfirmInfo"), CMessageBoxButton.OKCancel) == CMessageBoxResult.OK)
                        {
                            var facilityId = ClientInfo.EQPInfo.FacilityId;
                            var eqpname = ClientInfo.EQPInfo.TesterName;
                            EAPClient eapclient = new EAPClient();
                            //调用server getlotinfo
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            Dictionary<string, string> paramss = new Dictionary<string, string>();
                            paramss.Add("Lotid", Current.Lotid.ToUpper());
                            paramss.Add("eqpname", eqpname);
                            paramss.Add("UserId", ClientInfo.EQPInfo.LotList[0].UserId);
                            paramss.Add("facilityId", facilityId);
                            paramss.Add("proberCardId", Current.Probercardid.ToUpper());
                            paramss.Add("alignment", "None");
                            paramss.Add("testmode", "None");
                            SubBaseForm sb = new SubBaseForm("正在加载数据,请稍候...");
                            SubBaseForm.DelegateHasParmAndHasReturn my = new SubBaseForm.DelegateHasParmAndHasReturn(eapclient.GetCarrierLotInfo);
                            var obj = sb.HasParmAndHasReturnMethod(my, paramss);
                            //var _return = eapclient.GetCarrierLotInfo(Current.Lotid.ToUpper(), eqpname, ClientInfo.EQPInfo.LotList[0].UserId, facilityId, "None", "None");                                            
                            sw.Stop();
                            ServiceLogger.Debug($"Type2 调用GetCarrierLotInfo获取lot信息，耗时为:{sw.ElapsedMilliseconds}");
                            if (obj == null)
                            {
                                MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfoByType2"), MessageOrigin.EAP);
                                return;
                            }
                            var list = JsonConvert.DeserializeObject<Response<Object>>(obj.ReturnMessage);
                            if (list == null)
                            {
                                ServiceLogger.Debug($"_return: is null,{Dict.Current.EAPName}");
                                MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfoByType2"), MessageOrigin.EAP);
                                return;
                            }
                            if (list.Return.ReturnCode == "OK")
                            {
                                sw.Start();
                                var msgbody = list.Body;
                                msgbody.Units = JsonConvert.DeserializeObject<List<unitsInfo>>(msgbody.UnitList);
                                if (!string.IsNullOrEmpty(msgbody.SamplePrompts))
                                {
                                    msgbody.samplePrompts = JsonConvert.DeserializeObject<List<samplePrompts>>(msgbody.SamplePrompts);
                                }
                                ClientInfo.EQPInfo.LotList[0].LotId = msgbody.LotId;
                                ClientInfo.EQPInfo.LotList[0].LotsStatus = msgbody.LotStatus;
                                ClientInfo.EQPInfo.LotList[0].Qty = msgbody.WaferCount;
                                ClientInfo.EQPInfo.LotList[0].Priority = msgbody.Priority;
                                ClientInfo.EQPInfo.LotList[0].ProductId = msgbody.ProductId;
                                ClientInfo.EQPInfo.LotList[0].StageId = msgbody.StageId;
                                ClientInfo.EQPInfo.LotList[0].ProberRecipe = msgbody.ProberRecipe;
                                ClientInfo.EQPInfo.LotList[0].TesterProgram = msgbody.TesterProgram;
                                ClientInfo.EQPInfo.LotList[0].Probercard = Current.Probercardid;//TYPE 2 无Probercard

                                ClientInfo.EQPInfo.LotList[0].SlotMaps = new ObservableCollection<SLotMap>();

                                for (int i = 1; i <= 25; i++)
                                {
                                    ClientInfo.EQPInfo.LotList[0].SlotMaps.Add(new SLotMap() { SlotId = $"{i}", waferState = WaferState.WaferNothing.ToString() });//eaf5fd
                                }
                                var waferCode = "";
                                foreach (var item in msgbody.Units)
                                {
                                    var waferinfo = ClientInfo.EQPInfo.LotList[0].SlotMaps.First(o => o.SlotId == item.position);
                                    waferinfo.waferId = item.unitId;
                                    waferinfo.waferState = WaferState.WaferIn.ToString();
                                    waferinfo.runState = WaferState.Waiting.ToString();
                                    waferCode += item.t7code + ";";
                                }

                                //获取批次成功后，清除Lotid   
                                MainViewModel.Current.Lotid = "";
                                MainViewModel.Current.Probercardid = "";
                                ClientInfo.EQPInfo.BtnOk = Visibility.Collapsed;
                                MainViewModel.Current.ShowMsg(MessageType.Normal, ClientInfo.EQPInfo.LotList[0].LotId + "：" + Consts.GetTranslation("Msg_GetLotinfoOK"), MessageOrigin.EAP);
                                // true：EAP由mes信息自动传值，false:打开新的窗体，OP手动选片。  ps:选片的值需要client ->server-> OCR,。
                                if (AutoSelectWaferTest == true && !string.IsNullOrEmpty(msgbody.SamplePrompts))
                                {
                                    var testid = "";// 定义测试的id属性
                                    foreach (var item in msgbody.samplePrompts)
                                    {
                                        testid += item.position + ";";
                                    }
                                    ClientInfo.EQPInfo.LotList[0].TestID = testid.Replace(";", " ");  //前台显示测试的id ,id 之间用空格处理了
                                                                                                      //EAP获取片号进行传值
                                    var selectid = testid.TrimEnd(';');
                                    Dictionary<string, string> messages = null;
                                    var result = eapclient.SelectWaferID(ClientInfo.EQPInfo.ProberName, selectid, selectid, "true", "", waferCode);
                                    if (result.ReturnCode == "0")
                                    {
                                        messages = TranslateMsg.GetTranslation("SelectWaferIDOK", selectid);
                                        if (!(messages == null || messages.Count == 0))
                                        {
                                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                        }
                                        //  MainViewModel.Current.ShowMsg(MessageType.Info, ClientInfo.EQPInfo.LotList[0].LotId + "：" + "Select No" + tempID.TrimEnd(';'), MessageOrigin.EAP);
                                    }
                                    else
                                    {
                                        messages = TranslateMsg.GetTranslation("SelectWaferIDNG");
                                        if (!(messages == null || messages.Count == 0))
                                        {
                                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                                        }
                                    }
                                }
                                else
                                {
                                    //进行筛片                                 
                                    //  C_LotInfo lot = new C_LotInfo();
                                    lot.SelectWaferBox();
                                }
                                sw.Stop();
                                ServiceLogger.Debug($"Type2 调用GetCarrierLotInfo 结果不为空处理逻辑，耗时为:{sw.ElapsedMilliseconds}");
                            }
                            else
                                MainViewModel.Current.ShowMsg(MessageType.Error, "MES>" + list.Return.ReturnMessage, MessageOrigin.EAP);
                        }
                        else
                        {
                            ServiceLogger.Debug($"_return: is null,{Dict.Current.EAPName}");
                            MainViewModel.Current.ShowMsg(MessageType.Error, Consts.GetTranslation("Msg_GetLotinfoByType2"), MessageOrigin.EAP);

                        }
                    }

                }

                catch (Exception ex)
                {
                    ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
                }
            }));
        }
        /// <summary>
        /// //20220311取消wat特殊选片要求,选片function
        /// </summary>
        /// <param name="LotQty"></param>
        /// <param name="testid"></param>
        /// <returns></returns>
        public static string SelectWaferIdByWAT(string LotQty, string testid)
        {
            var lotqty = LotQty;
            var waferlist = "";
            string[] list = testid.Split(';');

            switch (lotqty)//
            {
                case "7":
                    //1,2,3,5,6,7
                    waferlist = list[0] + ";" + list[1] + ";" + list[2] + ";" + list[4] + ";" + list[5] + ";" + list[6];
                    break;
                case "8":
                    //1,2,4,5,7,8
                    waferlist = list[0] + ";" + list[1] + ";" + list[3] + ";" + list[4] + ";" + list[6] + ";" + list[8];
                    break;
                case "9":
                    //1,2,4,5,7,8
                    waferlist = list[0] + ";" + list[1] + ";" + list[3] + ";" + list[4] + ";" + list[6] + ";" + list[8];
                    break;
                case "10":
                    //1,2,4,6,8,10
                    waferlist = list[0] + ";" + list[1] + ";" + list[3] + ";" + list[5] + ";" + list[7] + ";" + list[9];
                    break;
                case "11":
                    //1,3,5,7,9,11
                    waferlist = list[0] + ";" + list[2] + ";" + list[4] + ";" + list[6] + ";" + list[8] + ";" + list[10];
                    break;
                case "12":
                    //1,3,5,7,9,11
                    waferlist = list[0] + ";" + list[2] + ";" + list[4] + ";" + list[6] + ";" + list[8] + ";" + list[10];
                    break;
                case "13":
                    //1,4,7,8,10,13
                    waferlist = list[0] + ";" + list[3] + ";" + list[6] + ";" + list[7] + ";" + list[9] + ";" + list[12];
                    break;
                case "14":
                    // 1,4,7,8,10,13
                    waferlist = list[0] + ";" + list[3] + ";" + list[6] + ";" + list[7] + ";" + list[9] + ";" + list[12];
                    break;
                case "15":
                    //1,4,7,10,13,15
                    waferlist = list[0] + ";" + list[3] + ";" + list[6] + ";" + list[9] + ";" + list[12] + ";" + list[14];
                    break;
                case "16":
                    //1,4,7,10,13,16
                    waferlist = list[0] + ";" + list[3] + ";" + list[6] + ";" + list[9] + ";" + list[12] + ";" + list[15];
                    break;
                case "17":
                    //1,4,7,10,13,16
                    waferlist = list[0] + ";" + list[3] + ";" + list[6] + ";" + list[9] + ";" + list[12] + ";" + list[15];
                    break;
                case "18":
                    //1,4,7,10,13,16
                    waferlist = list[0] + ";" + list[3] + ";" + list[6] + ";" + list[9] + ";" + list[12] + ";" + list[15];
                    break;
                case "19":
                    //1,5,9,13,16,19
                    waferlist = list[0] + ";" + list[4] + ";" + list[8] + ";" + list[12] + ";" + list[15] + ";" + list[18];
                    break;
                case "20":
                    //1,5,9,11,16,19
                    waferlist = list[0] + ";" + list[4] + ";" + list[8] + ";" + list[12] + ";" + list[15] + ";" + list[18];
                    break;
                case "21":
                    // 1,5,9,13,16,19
                    waferlist = list[0] + ";" + list[4] + ";" + list[8] + ";" + list[12] + ";" + list[15] + ";" + list[18];
                    break;
                case "22":
                    //4,8,10,14,18,20
                    waferlist = list[3] + ";" + list[7] + ";" + list[10] + ";" + list[13] + ";" + list[17] + ";" + list[19];
                    break;
                case "23":
                    // 3,7,12,17,22,23
                    waferlist = list[2] + ";" + list[6] + ";" + list[11] + ";" + list[16] + ";" + list[21] + ";" + list[22];
                    break;
                case "24":
                    //2,5,10,15,20,24
                    waferlist = list[1] + ";" + list[4] + ";" + list[9] + ";" + list[14] + ";" + list[19] + ";" + list[23];
                    break;
                case "25":
                    //1,6,11,16,21,25
                    waferlist = list[0] + ";" + list[5] + ";" + list[10] + ";" + list[15] + ";" + list[20] + ";" + list[24];
                    break;
            }
            return waferlist;
        }

        #endregion
        private RelayCommand stopProcessCmd;
        public RelayCommand StopProcessrCmd
        {
            get
            {
                return stopProcessCmd ?? (stopProcessCmd = new RelayCommand(StopProcess));
            }
        }
        private void StopProcess()
        {

            var testername = ClientInfo.EQPInfo.TesterName;
            var probername = ClientInfo.EQPInfo.ProberName;
            var USEID = ClientInfo.EQPInfo.LotList[0].UserId;
            EAPClient eapclient = new EAPClient();
            if (ClientInfo.EQPInfo.ConnText == "EAP OnLine")
            {
                if (CMessageBox.Show(Consts.GetTranslation("Msg_online") + "：" + "EAP OffLine" + "?", Consts.GetTranslation("Msg_ConfirmInfo"), CMessageBoxButton.OKCancel) == CMessageBoxResult.OK)
                {
                    //调用server false offline
                    var _return = eapclient.SendStopProcess(testername, probername);
                    if (_return != null && _return.ReturnCode == "0")
                    {
                        ClientInfo.EQPInfo.AuotoProcess = false;
                        ClientInfo.EQPInfo.LotList = new System.Collections.ObjectModel.ObservableCollection<C_LotInfo>();
                        ClientInfo.EQPInfo.LotList.Add(new C_LotInfo() { UserId = USEID });
                        var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                        Current.ShowMsg(MessageType.Info, messages[RunService.Current.ClientLanguage], MessageOrigin.EAP);
                    }
                }
            }
            else
            {
                if (CMessageBox.Show(Consts.GetTranslation("Msg_online") + "：" + "EAP OnLine" + "?", Consts.GetTranslation("Msg_ConfirmInfo"), CMessageBoxButton.OKCancel) == CMessageBoxResult.OK)
                {
                    //调用server true online
                    var _return = eapclient.StartProgram(testername, probername);
                    if (_return != null && _return.ReturnCode == "0")
                    {
                        ClientInfo.EQPInfo.AuotoProcess = true;
                        var messages = TranslateMsg.GetTranslation(CItems.AutomaticOperation);
                        Current.ShowMsg(MessageType.Info, messages[RunService.Current.ClientLanguage], MessageOrigin.EAP);
                    }
                }
            }

        }



        public void ChangeRGY(string color)
        {
            if (!string.IsNullOrEmpty(color))
            {
                if (color == Consts.YELLOW)
                    RGYColor = Consts.YELLOW;
                if (color == Consts.RED)
                    RGYColor = Consts.RED;
                if (color == Consts.GREEN)
                    RGYColor = Consts.GREEN;
            }
        }

        #region KVM
        public void ConnectKVM()
        {
            var pingIp = DataService.TestNetConnectity(ClientInfo.KvmInfo.KVMIP);
            if (!pingIp)
            {
                MainViewModel.Current.ShowMsg(MessageType.Error, $"KVM IP【{ClientInfo.KvmInfo.KVMIP}】无法连接，请检查网络...", MessageOrigin.EAP);
                return;
            }
            var appPath = $"{ClientInfo.KvmInfo.KVMIP}:{ClientInfo.KvmInfo.KVMPort}:0 -u {ClientInfo.KvmInfo.KVMUserName} -p {ClientInfo.KvmInfo.KVMPassword} -hkd -hkk -hkm -hks -hkg -hdo";
            var exePath = AppDomain.CurrentDomain.BaseDirectory + @"WinClient\WinClient";
            try
            {
                Thread thread = new Thread(() =>
                {
                    ClientInfo.KvmInfo.KvmProcess = new Process();
                    ClientInfo.KvmInfo.KvmProcess.StartInfo.FileName = exePath;
                    ClientInfo.KvmInfo.KvmProcess.StartInfo.Arguments = appPath;
                    ClientInfo.KvmInfo.KvmProcess.Start();
                    Thread.Sleep(ClientInfo.KvmInfo.KVMWaitFor); //程序未启动的时候，无法获取窗口的句柄。会造成process.MainWindowHandle返回值为0 加上延时
                    while (ClientInfo.KvmInfo.KvmProcess != null && ClientInfo.KvmInfo.KvmProcess.MainWindowHandle == IntPtr.Zero)
                    {
                        Thread.Sleep(100);
                    }
                    if (ClientInfo.KvmInfo.KvmProcess != null)
                    {
                        //this.KVMResize();
                        UpdateWinStyle.GetUpCaption(ClientInfo.KvmInfo.KvmProcess.MainWindowHandle);
                        //  Thread.Sleep(50);
                        Win32API.SetParent(ClientInfo.KvmInfo.KvmProcess.MainWindowHandle, ClientInfo.KvmInfo.KvmPanelHandle);
                    }
                });
                thread.IsBackground = true;
                thread.Start();
            }
            catch (Exception ex)
            {
                Current.ShowMsg(MessageType.Error, ex.Message, MessageOrigin.EAP);
            }
        }

        private void KVMResize()
        {
            //var result = Win32API.MoveWindow(kvmProcess.MainWindowHandle, 0, 0, width, height, true);
            KvmRect kvmRect;
            var result = Win32API.GetWindowRect(ClientInfo.KvmInfo.KvmProcess.MainWindowHandle, out kvmRect);
            var left = kvmRect.Left;
            var top = kvmRect.Top;
            int realWidth = (kvmRect.Right - kvmRect.Left);
            int realHeight = (kvmRect.Bottom - kvmRect.Top);//减去边框部分;
            Win32API.MoveWindow(ClientInfo.KvmInfo.KvmProcess.MainWindowHandle, left, top, realWidth, realHeight, true);
        }

        /// <summary>
        /// 断开KVM
        /// </summary>
        public void DisConnectKVM()
        {
            try
            {
                if (ClientInfo.KvmInfo.KvmProcess != null)
                {
                    if (!ClientInfo.KvmInfo.KvmProcess.CloseMainWindow()) //此处需判断返回值，已经调用CloseMainWindow后再强制Kill会报错
                    {
                        if (ClientInfo.KvmInfo.KvmProcess != null)
                            ClientInfo.KvmInfo.KvmProcess.Close();
                        if (ClientInfo.KvmInfo.KvmProcess != null)
                            ClientInfo.KvmInfo.KvmProcess.Kill();
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                ClientInfo.KvmInfo.KvmProcess = null;
            }
        }


        private RelayCommand reconnKVMCmd;
        public RelayCommand ReconnKVMCmd
        {
            get
            {
                return reconnKVMCmd ?? (reconnKVMCmd = new RelayCommand(ReconnKVM));
            }
        }

        private void ReconnKVM()
        {
            DisConnectKVM();
            ConnectKVM();
        }
        #endregion
    }
}
